<template>
	<view class="searchResult" v-if="!firstLoading">
		<search-header @focus="$go('/pages/search/index')"></search-header>
		<view class="content">
			<waterful-list v-if="articles.length != 0"
				:list="articles"
				:load="load"
				@itemClick="goArticleDetails"
			></waterful-list>
			<view class="none" v-else>
				<none-page></none-page>
			</view>
		</view>
	</view>
	<loading-page v-else></loading-page>
</template>

<script>
	import searchHeader from "../cpn/searchHeader.vue";
	import waterfulList from "@/components/waterfulList/waterfulList.vue";
	import nonePage from "@/components/none/none.vue";
	
	import {
		searchByCategory
	} from "@/api/search.js";
	
	export default {
		components: {
			searchHeader,
			waterfulList,
			nonePage
		},
		data() {
			return {
				categoryId: null,
				firstLoading: true,
				load: 'loadmore',
				pageInfo: {
					page: 1,
					pageSize: 20
				},
				articles: []
			}
		},
		computed: {
			
		},
		async onLoad(options) {
			if(options.id) this.categoryId = options.id;
			else this.$go("/pages/index/index");
			
			try{
				await this.getArticleByCategoryId();
			}catch(e){
				//TODO handle the exception
			}
			this.firstLoading = false;
		},
		methods: {
			// 获取文章
			getArticleByCategoryId() {
				// 当加载中或者无可加载则返回
				if(['loading', 'nomore'].indexOf(this.load) != -1) return;
				// 把加载状态改为加载中
				this.load = 'loading';
				console.log(this.categoryId)
				return new Promise((resolve, reject) => {
					searchByCategory({
						...this.pageInfo,
						categoryId: this.categoryId
					}).then(res => {
						this.articles = [...this.articles, ...res.articles];
						if(this.articles.length >= res.total) this.load = "nomore";
						else {
							this.load = "loadmore";
							this.pageInfo.page++;
						}
						resolve();
					}).catch(err => this.$msg(err.message));
				})
			},
			// 去文章详情页
			goArticleDetails(value) {
				this.$go("/pages/article/index",{
					id: value.id
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.searchResult{
	.none{
		// width: 100vw;
		// height: 100vh;
	}
}
</style>
